﻿using System.IO;
using System.Web;
using umbraco.BusinessLogic;
using umbraco.cms.businesslogic.media;
using Indexer=UmbSearch2.Search.Indexer;

namespace UmbSearch2.EventHandlers
{
	public class MediaIndexer : ApplicationBase
	{
		public MediaIndexer()
		{
			Media.AfterSave += Media_AfterSave;
			Media.BeforeDelete += Media_BeforeDelete;
		}

		public static void Media_BeforeDelete(Media sender, umbraco.cms.businesslogic.DeleteEventArgs e)
		{
			string relFilePath = "";

			if(sender.getProperty("umbracoFile") != null)
			{
				relFilePath = sender.getProperty("umbracoFile").Value.ToString();
			}
			// bug fix for accidental deleting of umbraco directory
			if (string.IsNullOrEmpty(relFilePath))
				return;

			string absFilePath = HttpContext.Current.Server.MapPath(relFilePath);
			string directoryToDelete = absFilePath.Remove(absFilePath.LastIndexOf("\\"));

			try
			{
				Directory.Delete(directoryToDelete, true);

				// remove node from index
				Indexer.RemoveNode(sender.Id);
			}
			catch (System.Exception ex)
			{
				Log.Add(LogTypes.Error, User.GetCurrent(), sender.Id, string.Format("Error removing media file from disk: {0}", ex));
			}
		}

		public static void Media_AfterSave(Media sender, umbraco.cms.businesslogic.SaveEventArgs e)
		{
			// after a file is removed
			if (string.IsNullOrEmpty(sender.getProperty("umbracoFile").Value.ToString()))
			{
				// remove node from index
				Indexer.RemoveNode(sender.Id);
			}
			// after a file is uploaded
			else
			{
				// add node to index
				Indexer.Index(sender);
			}
		}
	}
}